#include<iostream>
#include<pthread.h>
#include<unistd.h>
#include<string>
#include<vector>
#include<functional>
#include<time.h>
using namespace std;

//typedef std::function<void()> func_t;
using func_t = std:: function<void()>;//包装器

const int threadnum = 5;

class ThreadData
{
public:
    ThreadData(const std::string& name, const uint64_t& ctime, func_t f)
        :threadname(name)
        ,createtime(ctime)
        ,func(f)
        {}
public:
    std::string threadname;
    uint64_t createtime;
    func_t func;
};

void print()
{
    cout << "我是线程的执行任务的一部分" << endl;
}


void* ThreadRountine(void* args)
{
    int a = 10;
    ThreadData *td = static_cast<ThreadData *>(args);

    while (true)
    {
        std::cout << "new thread" << " thread name: " << td->threadname << " create time: " << td->createtime << std::endl;
        td->func();

        if(td->threadname == "thread-4")
        {
            cout << td->threadname << "触发异常" << endl;
        }
        sleep(1);
    } 

}


int main()
{
    //创建多线程
    vector<pthread_t> pthreads;
    for(size_t i = 0; i < threadnum; i++)
    {
        char threadname[64];
        snprintf(threadname, sizeof(threadname), "%s-%lu", "thread", i);

        pthread_t tid;
        ThreadData* td = new ThreadData(threadname, (uint64_t)time(nullptr), print);

        pthread_create(&tid, nullptr, ThreadRountine, td);
        pthreads.push_back(tid);
        sleep(1);
    }

    for(const auto& tid : pthreads)
    {
        cout << tid << endl;
    }

    while(true)
    {
        cout << "main thread" << endl;
    }
    
    return 0;
}